package com.wuyi.tea.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuyi.tea.domain.dto.AuthorizationDTO;
import com.wuyi.tea.domain.dto.TradeFormDTO;
import com.wuyi.tea.domain.dto.UserDTO;
import com.wuyi.tea.domain.pojo.User;
import com.wuyi.tea.enums.ConstantEnum;
import com.wuyi.tea.enums.ExceptionEnum;
import com.wuyi.tea.exception.AuthorizationException;
import com.wuyi.tea.exception.DataException;
import com.wuyi.tea.mapper.UserMapper;
import com.wuyi.tea.service.UserService;
import com.wuyi.tea.util.JwtUtil;
import com.wuyi.tea.util.LocalStorageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void topUp(TradeFormDTO tradeFormDTO) {

        // 1. 查询用户
        User user = userMapper.selectById(LocalStorageUtil.get().toString());

        // 2. 判断密码是否一致
        if (!user.getPassword().equals(tradeFormDTO.getPassword())){
            throw new AuthorizationException(ExceptionEnum.PASSWORD_ERROR);
        }

        // 3. 判断充值金额是否为负数
        if (tradeFormDTO.getTopUp().compareTo((double) 0)<0){
            throw new DataException(ExceptionEnum.MONEY_MINUS);
        }

        // 4.开始充值
        user.setBalance(user.getBalance() + tradeFormDTO.getTopUp());
        userMapper.updateById(user);
    }

    @Transactional
    @Override
    public void pay(TradeFormDTO tradeFormDTO) {

        // 1.获取用户信息
        User user = userMapper.selectById(LocalStorageUtil.get().toString());

        // 2.判断用户密码是否正确
        if (!user.getPassword().equals(tradeFormDTO.getPassword())){
            throw new AuthorizationException(ExceptionEnum.PASSWORD_ERROR);
        }

        // 3.判断用户支付金额是否是负数
        if (user.getBalance().compareTo((double) 0)<0){
            throw new DataException(ExceptionEnum.MONEY_MINUS);
        }

        // 4.判断用户余额是否足够支付
        if (user.getBalance() - tradeFormDTO.getPayMoney() < 0){
            throw new DataException(ExceptionEnum.BALANCE_LACK);
        }

        // 5.扣减用户余额
        user.setBalance(user.getBalance() - tradeFormDTO.getPayMoney());
        userMapper.updateById(user);

        // 6.管理端相加对应余额
        User admin = userMapper.selectById(ConstantEnum.ADMIN_ID);
        admin.setBalance(admin.getBalance() + tradeFormDTO.getPayMoney());

        userMapper.updateById(admin);
    }


    @Override
    public Double getByBalance(Long id) {
        User user = userMapper.selectById(id);
        return user !=null ? user.getBalance() : 0;
    }

    @Override
    public String login(AuthorizationDTO authorizationDTO) {

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername,authorizationDTO.getUsername())
                .eq(User::getPassword,authorizationDTO.getPassword())
        );

        if (Objects.isNull(user)){
            throw new AuthorizationException("用户名或密码错误");
        }

        // 登录成功，下发jwt令牌
        Map<String,Object>map= MapUtil.of("userId",user.getId());

        return JwtUtil.createJWT(map);
    }

    @Override
    public void register(AuthorizationDTO authorizationDTO) {

        // 1. 查出用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, authorizationDTO.getUsername())
        );

        // 2. 判断用户是否存在
        if (!Objects.isNull(user)){
            throw new AuthorizationException("用户名已存在");
        }

        // 3.注册用户信息
        user = User.builder()
                .username(authorizationDTO.getUsername())
                .password(authorizationDTO.getPassword())
                .avatar("http://120.26.247.145:9000/wuyi-tea/39e411df-6e03-4396-acd2-7f95b1efc489.jpg")
                .build();

        userMapper.insert(user);
    }

    @Override
    public void updateInfo(UserDTO userDto) {
        User userInfo = BeanUtil.copyProperties(userDto,User.class);
        userInfo.setId(Long.valueOf(LocalStorageUtil.get().toString()));
        userMapper.updateById(userInfo);
    }

}
